﻿Imports System.IO
Imports System.Net
Imports System.Net.Mail
Imports System.Text



Public Class form_发送邮件

    ' 相当于 VBA 里的“静态变量”
    Private strSmtpServer As String = "smtp.263.net"
    Private strFrom As String = "qj@shbrg.com"
    Private strFromPassword As String = "u7F&0Bsj"



    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        InitListView()
    End Sub



    Private Sub InitListView()
        With lv_附件列表
            .View = View.Details          ' = lvwReport
            .FullRowSelect = True
            .GridLines = True

            ' 清除旧列
            .Columns.Clear()
            .Columns.Add("文件名", 100, HorizontalAlignment.Left)
            .Columns.Add("文件路径", 400, HorizontalAlignment.Left)

            ' 清除旧行
            .Items.Clear()

            ' 允许拖放文件（等价于 VBA 的 lvOLEDropManual）
            .AllowDrop = True
            AddHandler .DragEnter, AddressOf lv_附件列表_DragEnter
            AddHandler .DragDrop, AddressOf lv_附件列表_DragDrop
        End With
    End Sub




    '' 简单的拖放实现示例
    'Private Sub lv_附件列表_DragEnter(sender As Object, e As DragEventArgs)
    '    'If e.Data.GetDataPresent(DataFormats.FileDrop) Then
    '    '    e.Effect = DragDropEffects.Copy
    '    'End If
    'End Sub

    'Private Sub lv_附件列表_DragDrop(sender As Object, e As DragEventArgs)
    '    'Dim files() As String = CType(e.Data.GetData(DataFormats.FileDrop), String())
    '    'For Each f In files
    '    '    Dim itm As New ListViewItem(IO.Path.GetFileName(f))
    '    '    itm.SubItems.Add(f)
    '    '    lv_附件列表.Items.Add(itm)
    '    'Next
    'End Sub




    ' 在 Form_Load 或设计器里加一次即可：
    ' lv_附件列表.AllowDrop = True
    ' AddHandler lv_附件列表.DragEnter, AddressOf lv_附件列表_DragEnter
    ' AddHandler lv_附件列表.DragDrop, AddressOf lv_附件列表_DragDrop

    Private Sub lv_附件列表_DragEnter(sender As Object, e As DragEventArgs)
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            e.Effect = DragDropEffects.Copy
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub





    Private Sub lv_附件列表_DragDrop(sender As Object, e As DragEventArgs)
        ' 取得拖进来的所有路径
        Dim paths As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())

        For Each filePath As String In paths

            If Directory.Exists(filePath) Then
                ' 是文件夹
                MessageBox.Show($"{filePath} 是文件夹，不能作为附件！", "提示",
                                MessageBoxButtons.OK, MessageBoxIcon.Information)
            Else
                ' 是文件
                Dim fileName As String = IO.Path.GetFileName(filePath)

                Dim item As New ListViewItem(fileName)
                item.SubItems.Add(filePath)
                lv_附件列表.Items.Add(item)
            End If
        Next
    End Sub



    Private Sub btn_删除附件_Click(sender As Object, e As EventArgs) Handles btn_删除附件.Click

        With lv_附件列表
            If .SelectedItems.Count > 0 Then
                If MessageBox.Show("确定要删除吗？", "确认",
                                   MessageBoxButtons.YesNo,
                                   MessageBoxIcon.Question) = DialogResult.Yes Then

                    ' 直接移除当前选中的第一项
                    .Items.Remove(.SelectedItems(0))
                End If
            Else
                MessageBox.Show("请先选择要删除的条目。", "提示",
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End If
        End With
    End Sub






    '''' <summary>
    '''' 发送按钮事件
    '''' </summary>
    'Private Sub btn_发送邮件_Click(sender As Object, e As EventArgs) _
    '    Handles btn_发送邮件.Click

    '    Try
    '        Using mail As New MailMessage()
    '            ' 发件人
    '            mail.From = New MailAddress(strFrom)

    '            ' 收件人 / 抄送
    '            mail.To.Add(txt_发送地址.Text.Trim())
    '            If Not String.IsNullOrWhiteSpace(txt_抄送地址.Text) Then
    '                mail.CC.Add(txt_抄送地址.Text.Trim())
    '            End If

    '            ' 主题
    '            mail.Subject = txt_邮件标题.Text.Trim()
    '            mail.SubjectEncoding = Encoding.UTF8

    '            ' 正文（RTF→HTML）
    '            Dim htmlBody As String = RTFToHTML(txt_邮件内容)
    '            mail.Body = htmlBody
    '            mail.IsBodyHtml = True
    '            mail.BodyEncoding = Encoding.UTF8

    '            ' 附件
    '            For Each itm As ListViewItem In lv_附件列表.Items
    '                Dim filePath As String = itm.SubItems(1).Text
    '                If File.Exists(filePath) Then
    '                    mail.Attachments.Add(New Attachment(filePath))
    '                End If
    '            Next

    '            ' SMTP 配置
    '            Using smtp As New SmtpClient(strSmtpServer, 465)
    '                smtp.Credentials = New NetworkCredential(strFrom, strFromPassword)
    '                smtp.EnableSsl = True
    '                smtp.Timeout = 60 * 1000

    '                smtp.Send(mail)
    '            End Using
    '        End Using

    '        MessageBox.Show("邮件已成功发送！", "完成",
    '                        MessageBoxButtons.OK, MessageBoxIcon.Information)

    '    Catch ex As Exception
    '        MessageBox.Show($"邮件发送失败：{ex.Message}", "错误",
    '                        MessageBoxButtons.OK, MessageBoxIcon.Error)
    '    End Try
    'End Sub




    ''' <summary>
    ''' 发送按钮事件
    ''' </summary>
    Private Sub btn_发送邮件_Click(sender As Object, e As EventArgs) _
    Handles btn_发送邮件.Click

        '' 1. 让 .NET 4.5+ 支持 TLS 1.2
        'System.Net.ServicePointManager.SecurityProtocol = Net.SecurityProtocolType.Tls12

        Try
            Using mail As New MailMessage()
                mail.From = New MailAddress(strFrom)
                mail.To.Add(txt_发送地址.Text.Trim())

                If Not String.IsNullOrWhiteSpace(txt_抄送地址.Text) Then
                    mail.CC.Add(txt_抄送地址.Text.Trim())
                End If

                mail.Subject = txt_邮件标题.Text.Trim()
                mail.SubjectEncoding = Encoding.UTF8

                ' RTF → HTML
                Dim htmlBody As String = RTFToHTML(txt_邮件内容)
                mail.Body = htmlBody
                mail.IsBodyHtml = True
                mail.BodyEncoding = Encoding.UTF8

                ' 附件
                For Each itm As ListViewItem In lv_附件列表.Items
                    Dim filePath As String = itm.SubItems(1).Text
                    If File.Exists(filePath) Then
                        mail.Attachments.Add(New Attachment(filePath))
                    End If
                Next

                ' 2. 端口改为 587，其余不变
                Using smtp As New SmtpClient(strSmtpServer, 587)
                    smtp.Credentials = New NetworkCredential(strFrom, strFromPassword)
                    smtp.EnableSsl = True
                    smtp.Timeout = 60 * 1000
                    smtp.Send(mail)
                End Using
            End Using

            MessageBox.Show("邮件已成功发送！", "完成",
                        MessageBoxButtons.OK, MessageBoxIcon.Information)

        Catch ex As Exception
            MessageBox.Show($"邮件发送失败：{ex.Message}", "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub


    ''' <summary>
    ''' 把 RichTextBox 的 RTF 转成 HTML
    ''' 这里给出一个极简实现：直接取 Text 作为纯文本。
    ''' 如需真正的 RTF→HTML，可引用 RtfPipe、GemBox、TX TextControl 等库。
    ''' </summary>
    Private Function RTFToHTML(rtb As RichTextBox) As String
        ' 简单方案：直接把纯文本包一层 <pre>
        Return $"<pre>{WebUtility.HtmlEncode(rtb.Text)}</pre>"
    End Function



End Class